package dao

import (
	"context"
	"fabric-explorer/entity"
	"fabric-explorer/tools"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson"
)

const (
	BLOCK_DATA_COLLECTION_NAME = "block_data"
)

//插入BlockData
func InsertBlockData(block entity.BlockData) {
	// tools.InitDB()
	collection := tools.GetCollection(BLOCK_DATA_COLLECTION_NAME)
	insertResult, err := collection.InsertOne(context.TODO(), block)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

//查询list
func FindBlockDataList(selecter bson.D) []entity.BlockData {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(BLOCK_DATA_COLLECTION_NAME)
	cur, err := collection.Find(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
	defer cur.Close(ctx)

	blockDataList := make([]entity.BlockData, 0)
	for cur.Next(ctx) {
		blockData := &entity.BlockData{}
		err := cur.Decode(blockData)
		if err != nil {
			fmt.Println(err)
		}
		blockDataList = append(blockDataList, *blockData)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	return blockDataList
}

//查询一个BlockData
func FindBlockDataOne(selecter bson.D) entity.BlockData {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(BLOCK_DATA_COLLECTION_NAME)
	oneResult := collection.FindOne(ctx, selecter)
	blockData := &entity.BlockData{}
	err := oneResult.Decode(blockData)
	if err != nil {
		fmt.Println(err)
	}
	return *blockData
}

//删除blockData
func DeleteblockData(selecter bson.D) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(BLOCK_DATA_COLLECTION_NAME)
	_, err := collection.DeleteMany(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
}
